package com.prim.threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * 展示wait和notify的基本用法
 * 代码执行顺序
 * 证明wait是释放锁的
 *
 * @author prim
 */
public class Wait {
    public static Object object = new Object();

    static class Thread1 extends Thread {
        @Override
        public void run() {
            //线程1 先获得锁来证明wait会释放锁
            synchronized (object) {
                System.out.println(Thread.currentThread().getName() + "开始执行了");
                try {
                    object.wait();//释放锁 等待期间遇到中断会抛出异常
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程" + Thread.currentThread().getName() + "状态为：" + Thread.currentThread().getState());
                System.out.println("重新获得了锁" + Thread.currentThread().getName());
            }
        }
    }

    static class Thread2 extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                //唤醒
                object.notify();
                System.out.println("线程" + Thread.currentThread().getName() + "调用了notify");
                System.out.println("线程" + thread1.getName() + "状态为：" + thread1.getState());
            }
            //synchronized 同步块代码执行完毕之后 才会释放锁
            System.out.println("线程" + Thread.currentThread().getName() + "释放锁");
        }
    }

    static Thread1 thread1 = new Thread1();
    static Thread2 thread2 = new Thread2();

    public static void main(String[] args) throws InterruptedException {
        thread1.start();
        Thread.sleep(200);
        thread2.start();
    }
}
